const httpStatus = require('http-status');
const ApiError = require('../utils/ApiError');
const catchAsync = require('../utils/catchAsync');
const { nutritionGoalService, nutritionSuggestionService, nutritionAnalysisService } = require('../services');
const mongoose = require('mongoose');

/**
 * 创建用户营养目标
 */
const createNutritionGoal = catchAsync(async (req, res) => {
  const userIdToUse = req.body.userId ? req.body.userId : req.user?.id;
  if (!userIdToUse || !mongoose.Types.ObjectId.isValid(userIdToUse)) {
    throw new ApiError(httpStatus.BAD_REQUEST, '有效的用户ID是必需的');
  }

  const goalData = { ...req.body, userId: userIdToUse };
  const nutritionGoal = await nutritionGoalService.createNutritionGoal(goalData);
  
  res.status(httpStatus.CREATED).send({
    error: 0,
    body: nutritionGoal,
    message: '营养目标创建成功',
  });
});

/**
 * 获取用户营养目标
 */
const getNutritionGoal = catchAsync(async (req, res) => {
  const userId = req.params.userId;
  const nutritionGoal = await nutritionGoalService.getNutritionGoalByUserId(userId);
  
  if (!nutritionGoal) {
    throw new ApiError(httpStatus.NOT_FOUND, '未找到用户的营养目标');
  }
  
  res.send({
    error: 0,
    body: nutritionGoal,
    message: '获取营养目标成功',
  });
});

/**
 * 更新用户营养目标
 */
const updateNutritionGoal = catchAsync(async (req, res) => {
  const userId = req.params.userId;
  const nutritionGoal = await nutritionGoalService.updateNutritionGoal(userId, req.body);
  
  res.send({
    error: 0,
    body: nutritionGoal,
    message: '营养目标更新成功',
  });
});

/**
 * 删除用户营养目标
 */
const deleteNutritionGoal = catchAsync(async (req, res) => {
  const userId = req.params.userId;
  await nutritionGoalService.deleteNutritionGoal(userId);
  
  res.send({
    error: 0,
    body: null,
    message: '营养目标删除成功',
  });
});

/**
 * 创建营养建议
 */
const createNutritionSuggestion = catchAsync(async (req, res) => {
  const userIdToUse = req.body.userId ? req.body.userId : req.user?.id;
  if (!userIdToUse || !mongoose.Types.ObjectId.isValid(userIdToUse)) {
    throw new ApiError(httpStatus.BAD_REQUEST, '有效的用户ID是必需的');
  }

  const suggestionData = { ...req.body, userId: userIdToUse };
  const nutritionSuggestion = await nutritionSuggestionService.createNutritionSuggestion(suggestionData);
  
  res.status(httpStatus.CREATED).send({
    error: 0,
    body: nutritionSuggestion,
    message: '营养建议创建成功',
  });
});

/**
 * 获取营养建议列表
 */
const getNutritionSuggestions = catchAsync(async (req, res) => {
  const filter = {};
  
  // 若指定了userId则过滤，否则可以查询所有用户的建议（管理员接口）
  if (req.query.userId) {
    filter.userId = req.query.userId;
  }
  
  // 其他过滤条件
  if (req.query.type) filter.type = req.query.type;
  if (req.query.isRead !== undefined) filter.isRead = req.query.isRead === 'true';
  if (req.query.startDate) filter.startDate = req.query.startDate;
  if (req.query.endDate) filter.endDate = req.query.endDate;
  
  const options = {
    sortBy: req.query.sortBy,
    limit: req.query.limit ? parseInt(req.query.limit, 10) : 10,
    page: req.query.page ? parseInt(req.query.page, 10) : 1,
  };
  
  const result = await nutritionSuggestionService.queryNutritionSuggestions(filter, options);
  
  res.send({
    error: 0,
    body: result,
    message: '获取营养建议列表成功',
  });
});

/**
 * 获取单条营养建议
 */
const getNutritionSuggestion = catchAsync(async (req, res) => {
  const suggestion = await nutritionSuggestionService.getNutritionSuggestionById(req.params.id);
  
  res.send({
    error: 0,
    body: suggestion,
    message: '获取营养建议成功',
  });
});

/**
 * 更新营养建议
 */
const updateNutritionSuggestion = catchAsync(async (req, res) => {
  const suggestion = await nutritionSuggestionService.updateNutritionSuggestion(req.params.id, req.body);
  
  res.send({
    error: 0,
    body: suggestion,
    message: '营养建议更新成功',
  });
});

/**
 * 删除营养建议
 */
const deleteNutritionSuggestion = catchAsync(async (req, res) => {
  await nutritionSuggestionService.deleteNutritionSuggestion(req.params.id);
  
  res.send({
    error: 0,
    body: null,
    message: '营养建议删除成功',
  });
});

/**
 * 标记用户所有营养建议为已读
 */
const markAllSuggestionsAsRead = catchAsync(async (req, res) => {
  const userId = req.params.userId;
  const result = await nutritionSuggestionService.markAllSuggestionsAsRead(userId);
  
  res.send({
    error: 0,
    body: result,
    message: `已将用户的 ${result.modifiedCount} 条营养建议标记为已读`,
  });
});

/**
 * 获取用户营养分析数据
 */
const getNutritionAnalysis = catchAsync(async (req, res) => {
  const userId = req.query.userId ? req.query.userId : req.user?.id;
  if (!userId || !mongoose.Types.ObjectId.isValid(userId)) {
    throw new ApiError(httpStatus.BAD_REQUEST, '有效的用户ID是必需的');
  }
  
  const options = {
    userId,
    period: req.query.period || 'week',
  };
  
  if (req.query.startDate) options.startDate = req.query.startDate;
  if (req.query.endDate) options.endDate = req.query.endDate;
  
  const analysisResult = await nutritionAnalysisService.getNutritionAnalysis(options);
  
  res.send({
    error: 0,
    body: analysisResult,
    message: '获取营养分析成功',
  });
});

/**
 * 获取热量摄入趋势
 */
const getCaloriesTrend = catchAsync(async (req, res) => {
  const userId = req.query.userId ? req.query.userId : req.user?.id;
  if (!userId || !mongoose.Types.ObjectId.isValid(userId)) {
    throw new ApiError(httpStatus.BAD_REQUEST, '有效的用户ID是必需的');
  }
  
  const options = {
    userId,
    period: req.query.period || '7'
  };
  
  const trendData = await nutritionAnalysisService.getCaloriesTrend(options);
  
  res.send({
    error: 0,
    body: trendData,
    message: '获取热量摄入趋势成功',
  });
});

/**
 * 获取营养素比例
 */
const getNutrientRatio = catchAsync(async (req, res) => {
  const userId = req.query.userId ? req.query.userId : req.user?.id;
  if (!userId || !mongoose.Types.ObjectId.isValid(userId)) {
    throw new ApiError(httpStatus.BAD_REQUEST, '有效的用户ID是必需的');
  }
  
  const options = {
    userId,
    period: req.query.period || 'today'
  };
  
  const ratioData = await nutritionAnalysisService.getNutrientRatio(options);
  
  res.send({
    error: 0,
    body: ratioData,
    message: '获取营养素比例成功',
  });
});

/**
 * 获取营养素详情
 */
const getNutrientDetails = catchAsync(async (req, res) => {
  const userId = req.query.userId ? req.query.userId : req.user?.id;
  if (!userId || !mongoose.Types.ObjectId.isValid(userId)) {
    throw new ApiError(httpStatus.BAD_REQUEST, '有效的用户ID是必需的');
  }
  
  const options = {
    userId,
    period: req.query.period || 'today'
  };
  
  const detailsData = await nutritionAnalysisService.getNutrientDetails(options);
  
  res.send({
    error: 0,
    body: detailsData,
    message: '获取营养素详情成功',
  });
});

/**
 * 修复 NutritionSuggestion 接口
 * 确保能返回绘图所需的营养建议
 */
const generateNutritionSuggestions = catchAsync(async (req, res) => {
  // 添加详细调试日志
  console.log('==== generateNutritionSuggestions ====');
  console.log('req.params:', JSON.stringify(req.params));
  console.log('req.query:', JSON.stringify(req.query));
  console.log('req.user:', req.user ? JSON.stringify({id: req.user.id}) : 'null');
  
  let userId;
  try {
    userId = req.query.userId ? req.query.userId : req.user?.id;
    console.log('使用的userId:', userId);
    
    if (!userId) {
      console.log('未找到userId！');
      throw new ApiError(httpStatus.BAD_REQUEST, '未提供用户ID');
    }
    
    // 验证userId是否为有效的MongoDB ID
    if (!mongoose.Types.ObjectId.isValid(userId)) {
      console.log('无效的MongoDB ID:', userId);
      throw new ApiError(httpStatus.BAD_REQUEST, '有效的用户ID是必需的');
    }
    
    // 获取用户的营养分析数据
    const options = {
      userId,
      period: 'week' // 基于最近一周的数据生成建议
    };
    
    console.log('准备获取营养素详情，options:', JSON.stringify(options));
    
    // 1. 获取营养素详情
    const { nutrients } = await nutritionAnalysisService.getNutrientDetails(options);
    console.log('获取到的营养素详情:', JSON.stringify(nutrients));
    
    // 2. 根据营养素摄入状况生成建议
    // 这里手动生成UI中展示的固定建议，实际应该根据分析结果动态生成
    const suggestions = [
      {
        type: 'protein',
        icon: 'protein_icon',
        title: '增加蛋白质摄入',
        content: '建议增加瘦肉、水果和谷物的摄入，提高蛋白质供给量。',
        color: '#E1F5FE',
        isRead: false
      },
      {
        type: 'water',
        icon: 'water_icon',
        title: '增加水分摄入',
        content: '每日饮水量建议达到2000ml以上，保持身体充分水合。',
        color: '#E3F2FD',
        isRead: false
      },
      {
        type: 'protein_source',
        icon: 'protein_source_icon',
        title: '优化蛋白质来源',
        content: '建议增加瘦肉、鱼类和豆制品摄入，减少红肉和加工肉制品摄入。',
        color: '#FFF3E0',
        isRead: false
      },
      {
        type: 'sodium',
        icon: 'sodium_icon',
        title: '注意钠盐摄入',
        content: '建议减少调味料和加工食品的摄入，适量增加水果摄量。',
        color: '#FFEBEE',
        isRead: false
      }
    ];
    
    console.log('生成的建议数量:', suggestions.length);
    
    // 3. 保存建议到数据库（如果需要）
    // 这里简化处理，直接返回生成的建议
    // 实际使用中可能需要先保存到NutritionSuggestion表再返回
    
    res.send({
      error: 0,
      body: { suggestions },
      message: '获取营养建议成功',
    });
  } catch (error) {
    console.log('生成建议时出错:', error.message);
    console.log('错误堆栈:', error.stack);
    throw error;
  }
});

module.exports = {
  // 营养目标相关
  createNutritionGoal,
  getNutritionGoal,
  updateNutritionGoal,
  deleteNutritionGoal,
  
  // 营养建议相关
  createNutritionSuggestion,
  getNutritionSuggestions,
  getNutritionSuggestion,
  updateNutritionSuggestion,
  deleteNutritionSuggestion,
  markAllSuggestionsAsRead,
  
  // 营养分析相关
  getNutritionAnalysis,
  getCaloriesTrend,
  getNutrientRatio,
  getNutrientDetails,
  generateNutritionSuggestions,
};